package com.luyu.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.luyu.OpenfeignConstant;
import com.luyu.service.PermissionService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;

@Component("rbac")
public class AccessByRoleUtil {

    @Resource
    private PermissionService permissionService;

    /**
     * todo 待升级 ，权限码写死了，能不能换一种方式进行切割uri判断处理
     * 是否允许内部调用，是就可以直接跳过权限校验
     * @param permission 权限码
     * @param openfeignAllow 是否是内部调用
     * @return 是否有权限访问
     */
    public boolean hasPermission(String permission,Boolean openfeignAllow) {
        Boolean hashPermission=false;
        // 如果没有权限码或者没有登录都视为不可接触
        if (StrUtil.isBlank(permission)||ObjUtil.isNull(SecurityContextHolder.getContext().getAuthentication())) {
            return hashPermission;
        }

        // 处理内部调用接口允许放行
        if (openfeignAllow){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            hashPermission= StrUtil.isNotBlank(request.getHeader(OpenfeignConstant.openfeignHeaderName));
        }
        // 从数据库查询处理
        if (!hashPermission){
            List<Long> roleIds = permissionService.listRoleIdsByPermissionCode(permission);
            Long currentRoleId = UserContextUtil.getUserCurrentRoleId();
            if (CollUtil.isNotEmpty(roleIds)&& ObjUtil.isNotNull(currentRoleId)){
                hashPermission= roleIds.contains(currentRoleId);
            }
        }


        return hashPermission;
    }


}
